package com.qf.controller;

import com.qf.captcha.CaptchaCodeManager;
import com.qf.util.*;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/*
 *@Description:
 *@author:刘哥
 *@Date:14:05 2022/7/25
 */
@RestController
//允许跨域
@CrossOrigin("*")
@RequestMapping("/auth")
public class AuthController {
    @RequestMapping("/captchaImage")
    public Object getCodeImage(HttpServletResponse response){
        //1. 生成4位随机验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //2. 生成验证码唯一id
        String uuid = UUID.randomUUID().toString(true);
//将验证码存储到内存中
        boolean flag = CaptchaCodeManager.addToCache(uuid, code, 2);
//        判断验证码是否存储成功
        if(!flag){
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_AUTH);
        }
//        生成验证码的图片
//        通过流创建
        ByteOutputStream out = new ByteOutputStream();
        try {
            VerifyCodeUtils.outputImage(100,40,out,code);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        将验证码唯一的id和图片内容返回
        Map<String, String> result = new HashMap<>();
//      将图片地址使用base64加密，防止中文乱码
        result.put("img", Base64.encode(out.toByteArray()));
        result.put("uuid",uuid);
        return ResponseUtil.ok(result);
    }
    @RequestMapping("/login")
    public Object login(@RequestBody String param){
//        提取前端传来的json参数
//        用户输入的用户名
        String username = JacksonUtil.parseString(param, "username");
        //        用户输入的密码
        String password = JacksonUtil.parseString(param, "password");
//        用户输入的验证码
        String code = JacksonUtil.parseString(param, "code");
//        获取验证码的uuid
        String uuid = JacksonUtil.parseString(param, "uuid");
        if(StringUtils.isEmpty(code)){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_EXPIRED);
        }
        if(StringUtils.isEmpty(username)){
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        }
        if(StringUtils.isEmpty(password)){
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        }
        if(StringUtils.isEmpty(uuid)){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_EXPIRED);
        }
//        校验验证码是否正确
        String cacheCode = CaptchaCodeManager.getCachedCaptcha(uuid);
        if(!code.equalsIgnoreCase(cacheCode)){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
        }
//        创建subject对象
        Subject subject = SecurityUtils.getSubject();
//        创建token对象
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        } catch (AuthenticationException e) {
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_AUTH);
        }

//      获取用户登录成功后再shiro框架的session会回话中的唯一id，返回给前端
        return ResponseUtil.ok(subject.getSession().getId());
    }


}